using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.productpurchaseprices;
using SupplierCustomerManagement.Read.API.Dtos;
using SupplierCustomerManagement.Infrastructure;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.productpurchaseprices
{
    /// <summary>
    /// 获取商品采购价格列表查询命令处理器
    /// </summary>
    public class GetProductPurchasePricesQueryHandler : IRequestHandler<GetProductPurchasePricesQuery, ApiPaging<ProductPurchasePriceListDto>>
    {
        private readonly SupplierDbContext _dbContext;
        private readonly ILogger<GetProductPurchasePricesQueryHandler> _logger;

        public GetProductPurchasePricesQueryHandler(
            SupplierDbContext dbContext,
            ILogger<GetProductPurchasePricesQueryHandler> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取商品采购价格列表查询命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果</returns>
        public async Task<ApiPaging<ProductPurchasePriceListDto>> Handle(GetProductPurchasePricesQuery request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建基础查询 - 使用LEFT JOIN避免导航属性问题
                var query = from p in _dbContext.ProductPurchasePrices
                           join s in _dbContext.Suppliers on p.SupplierId equals s.Id into supplierJoin
                           from supplier in supplierJoin.DefaultIfEmpty()
                           where !p.IsDeleted
                           select new
                           {
                               p.Id,
                               p.SupplierId,
                               SupplierName = supplier != null ? supplier.SupplierName : "",
                               p.ProductName,
                               p.Specification,
                               p.MeasurementUnit,
                               p.InvoicePrice,
                               p.SettlementPrice,
                               p.Discount,
                               p.PublicPrice,
                               p.StartDate,
                               p.EndDate,
                               p.SchemeName,
                               p.Remarks,
                               p.CreatedTime,
                               p.UpdatedTime
                           };

                // 应用筛选条件
                if (request.SupplierId.HasValue)
                {
                    query = query.Where(p => p.SupplierId == request.SupplierId.Value);
                }

                if (!string.IsNullOrWhiteSpace(request.ProductName))
                {
                    query = query.Where(p => p.ProductName.Contains(request.ProductName));
                }

                if (!string.IsNullOrWhiteSpace(request.Specification))
                {
                    query = query.Where(p => p.Specification.Contains(request.Specification));
                }

                if (!string.IsNullOrWhiteSpace(request.SchemeName))
                {
                    query = query.Where(p => p.SchemeName.Contains(request.SchemeName));
                }

                // 默认按创建时间降序排序
                query = query.OrderByDescending(p => p.CreatedTime);

                // 获取总数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页
                var skip = (request.PageIndex - 1) * request.PageSize;
                var items = await query
                    .Skip(skip)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 直接映射到DTO
                var dtoItems = items.Select(p => new ProductPurchasePriceListDto
                {
                    Id = p.Id,
                    SupplierId = p.SupplierId,
                    SupplierName = p.SupplierName ?? string.Empty,
                    ProductName = p.ProductName,
                    Specification = p.Specification,
                    MeasurementUnit = p.MeasurementUnit,
                    InvoicePrice = p.InvoicePrice,
                    SettlementPrice = p.SettlementPrice,
                    Discount = p.Discount,
                    PublicPrice = p.PublicPrice,
                    StartDate = p.StartDate,
                    EndDate = p.EndDate,
                    SchemeName = p.SchemeName,
                    Remarks = p.Remarks,
                    CreatedTime = p.CreatedTime,
                    UpdatedTime = p.UpdatedTime
                }).ToList();

                // 构建分页结果
                var result = new ApiPaging<ProductPurchasePriceListDto>
                {
                    PageData = dtoItems,
                    TotalCount = totalCount,
                    PageCount = (int)Math.Ceiling((double)totalCount / request.PageSize)
                };

                _logger.LogInformation("成功获取商品采购价格列表，总数: {TotalCount}, 页码: {PageIndex}, 页大小: {PageSize}", 
                    totalCount, request.PageIndex, request.PageSize);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取商品采购价格列表时发生异常");
                throw;
            }
        }
    }
} 